import Layout from '@/layout/index'
export function filterAsyncRouter (data) {
  data.forEach(item => {
    if (item.component === 'Layout') {
      item.component = Layout
    } else {
      item.component = loadViews(item.component)
    }
    // 判断 当前菜单是否有下级菜单
    if (item.children) {
      filterAsyncRouter(item.children)
    }
  })
  return data
}

function loadViews (path) {
  return resolve => require([`@/views/${path}.vue`], resolve)
}

// 通过注册自定义指令v-permission
export default {
  inserted (el, binding, vnode) {
    // 自定义指令后绑定的值
    const { value } = binding
    // 获取所有的权限集合
    const roles = localStorage.getItem('roles') ? JSON.parse(localStorage.getItem('roles')) : []
    // value 存在数组 并且数组长度>0
    if (value && value instanceof Array && value.length > 0) {
      // ['user:add','admin']
      const permissionRoles = value
      // roles -> ['*'] 当前用户的所有权限
      // some 有真为真，every 全真为真
      const hasPermission = roles.some(role => {
        // includes 包含
        // 得到的是Boolean
        return permissionRoles.includes(role)
      })

      if (!hasPermission) {
        // el 是当前dom节点
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('need roles! Like v-permission="["admin","editor"]"')
    }
  }
}
